package com.test.chat;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
* @类名  MyServer.java
* @作者  jinbanglong
* @版本  V1.0
* @日期  2019年6月23日-下午2:17:47
* @描述  
*
*/
public class MyServer {
	static HashMap<String,Socket> map= new HashMap<>();
	public static void main(String[] args) {
		try {
			ServerSocket ss= new ServerSocket(6666);
			while(true) {
				Socket sk = ss.accept();
				System.out.println(sk);
				 new Thread(new Server(sk)).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
	}

}
class Server implements Runnable{
	DataOutputStream DS;
	DataInputStream console;
	public Server(Socket sk) {
		try {
			console = new  DataInputStream(sk.getInputStream());
			DS = new DataOutputStream(sk.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	@Override
	public void run() {
		String msg=null;
		 try {
			 while(true) {
				String fname = String.valueOf(System.currentTimeMillis()/1000);
				String dir ="img";
				String path = "D:\\dev\\apache-tomcat-8.5.42\\webapps";
				fname=console.readUTF();
				String newName = path+"\\"+dir+"\\"+fname;
				File file = new File(newName); 
				FileOutputStream fos = new FileOutputStream(file);
				DataOutputStream dd = new DataOutputStream(fos);
				long length= console.readLong();
				byte[] b = new byte[1024];
				int len;
				int lens=0;
				while((len=console.read(b))!=-1) {
					dd.write(b, 0, len);
					lens+=len;
					dd.flush();
					if(lens==length){
						break;
					}
				}
				//向客户端返回上传地址
				
				InetAddress addr = InetAddress.getLocalHost(); 
				String url="http://"+addr.getHostAddress()+":8080/"+dir+"/"+fname;
				DS.writeUTF(url);
			 }
		 } catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	//文件上传处理方法
	public void upload() {
		
		
		
	}
	//聊天记录存储方法
	public void chatLog() {
		
	}
	
	
}